{{define "content"}}
<!-- Toast 通知组件 -->
<div id="toast-container" class="fixed top-4 right-4 z-50 space-y-2"></div>

<script>
    // 全局 Toast 函数
    window.showToast = function(message, type = 'info', duration = 3000) {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        
        const typeClasses = {
            success: 'bg-green-50 border-green-200 text-green-800',
            error: 'bg-red-50 border-red-200 text-red-800',
            warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
            info: 'bg-blue-50 border-blue-200 text-blue-800'
        };
        
        const iconClasses = {
            success: 'fas fa-check-circle text-green-500',
            error: 'fas fa-times-circle text-red-500',
            warning: 'fas fa-exclamation-triangle text-yellow-500',
            info: 'fas fa-info-circle text-blue-500'
        };
        
        toast.className = `max-w-sm w-full ${typeClasses[type]} border rounded-lg shadow-lg p-4 transform transition-all duration-300 translate-x-full opacity-0`;
        toast.innerHTML = `
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <i class="${iconClasses[type]}"></i>
                </div>
                <div class="ml-3 flex-1">
                    <p class="text-sm font-medium">${message}</p>
                </div>
                <div class="ml-4 flex-shrink-0">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        }, 10);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }, duration);
    };
</script>

<div x-data="editUserForm()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">编辑用户</h1>
                <p class="text-gray-600">修改用户信息和权限</p>
            </div>
            <div>
                <a href="/system/users" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i>
                    返回用户列表
                </a>
            </div>
        </div>
    </div>

    <!-- 编辑用户表单 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">用户信息</h3>
                <div x-show="hasChanges" class="flex items-center text-amber-600">
                    <i class="fas fa-exclamation-circle mr-2"></i>
                    <span class="text-sm font-medium">有未保存的更改</span>
                </div>
            </div>
        </div>
        
        <div x-show="isLoading" class="p-6 text-center">
            <i class="fas fa-spinner fa-spin text-blue-500 text-2xl"></i>
            <p class="mt-2 text-gray-600">加载用户信息...</p>
        </div>
        
        <form x-show="!isLoading" @submit.prevent="submitForm()" class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 基本信息 -->
                <div class="space-y-6">
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2">基本信息</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">用户名</label>
                        <input type="text" 
                               x-model="form.username" 
                               disabled
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 bg-gray-100">
                        <p class="mt-1 text-sm text-gray-500">用户名不可修改</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">真实姓名 <span class="text-red-500">*</span></label>
                        <input type="text" 
                               x-model="form.real_name" 
                               required 
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">新密码</label>
                        <input type="password" 
                               x-model="form.new_password" 
                               minlength="6"
                               autocomplete="new-password"
                               data-lpignore="true"
                               data-form-type="other"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p class="mt-1 text-sm text-gray-500">留空表示不修改密码，新密码长度至少6位</p>
                    </div>
                    
                    <div x-show="form.new_password">
                        <label class="block text-sm font-medium text-gray-700">确认新密码</label>
                        <input type="password" 
                               x-model="form.confirm_password" 
                               minlength="6"
                               autocomplete="new-password"
                               data-lpignore="true"
                               data-form-type="other"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p x-show="errors.confirm_password" class="mt-1 text-sm text-red-600" x-text="errors.confirm_password"></p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">状态</label>
                        <select x-model="form.status" 
                                class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="active">活跃</option>
                            <option value="inactive">停用</option>
                        </select>
                    </div>
                </div>
                
                <!-- 联系方式和角色 -->
                <div class="space-y-6">
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2">联系方式</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">手机号</label>
                        <input type="tel" 
                               x-model="form.phone" 
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">邮箱</label>
                        <input type="email" 
                               x-model="form.email" 
                               @blur="checkEmail()"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p x-show="errors.email" class="mt-1 text-sm text-red-600" x-text="errors.email"></p>
                    </div>
                    
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2 mt-8">角色分配</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择角色</label>
                        <div class="space-y-2 max-h-64 overflow-y-auto border border-gray-300 rounded-md p-3">
                            <template x-for="role in roles" :key="role.id">
                                <label class="flex items-center p-2 hover:bg-gray-50 rounded">
                                    <input type="checkbox" 
                                           :value="role.id" 
                                           @change="toggleRole(role.id)" 
                                           :checked="form.role_ids.includes(role.id)" 
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900" x-text="role.display_name"></div>
                                        <div class="text-sm text-gray-500" x-text="role.description"></div>
                                    </div>
                                </label>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="mt-8 border-t pt-6">
                <div class="flex justify-between">
                    <div class="flex space-x-4">
                        <button type="button" 
                                @click="resetForm()"
                                :disabled="!hasChanges || isSubmitting"
                                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
                            <i class="fas fa-undo mr-2"></i>重置
                        </button>
                    </div>
                    <div class="flex space-x-3">
                        <button type="button" 
                                @click="cancelEdit()"
                                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            取消
                        </button>
                        <button type="submit" 
                                :disabled="isSubmitting || !hasChanges"
                                class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
                            <span x-show="isSubmitting">
                                <i class="fas fa-spinner fa-spin mr-2"></i>保存中...
                            </span>
                            <span x-show="!isSubmitting">保存更改</span>
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function editUserForm() {
    return {
        // 表单数据
        form: {
            id: '',
            username: '',
            real_name: '',
            new_password: '',
            confirm_password: '',
            phone: '',
            email: '',
            status: 'active',
            role_ids: []
        },
        
        originalForm: {},
        
        // 错误信息
        errors: {
            email: '',
            confirm_password: ''
        },
        
        // 状态
        isLoading: true,
        isSubmitting: false,
        hasChanges: false,
        roles: [],
        userId: null,
        
        // 初始化
        async init() {
            // 从URL获取用户ID
            const urlParts = window.location.pathname.split('/');
            this.userId = urlParts[urlParts.length - 1];
            
            // 并行加载数据
            await Promise.all([
                this.loadUserData(),
                this.loadRoles()
            ]);
            
            this.isLoading = false;
            
            // 监听表单变化
            this.$watch('form', () => {
                this.checkForChanges();
            }, { deep: true });
            
            // 页面离开前提醒
            window.addEventListener('beforeunload', (e) => {
                if (this.hasChanges) {
                    e.preventDefault();
                    e.returnValue = '您有未保存的更改，确定要离开吗？';
                }
            });
        },
        
        // 加载用户数据
        async loadUserData() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    const userData = result.data;
                    
                    this.form.id = userData.id;
                    this.form.username = userData.username;
                    this.form.real_name = userData.real_name;
                    this.form.phone = userData.phone || '';
                    this.form.email = userData.email || '';
                    this.form.status = userData.status;
                    
                    // 加载用户角色
                    const rolesResponse = await fetch(`/api/v1/users/${this.userId}/roles`);
                    const rolesResult = await rolesResponse.json();
                    
                    if (rolesResult.code === 200 && rolesResult.data) {
                        this.form.role_ids = rolesResult.data.map(role => role.id);
                    }
                    
                    // 保存原始数据用于比较
                    this.originalForm = JSON.parse(JSON.stringify(this.form));
                } else {
                    throw new Error(result.message || '获取用户数据失败');
                }
            } catch (error) {
                console.error('加载用户数据失败:', error);
                this.showToast('加载用户数据失败: ' + error.message, 'error');
                setTimeout(() => {
                    window.location.href = '/system/users';
                }, 1500);
            }
        },
        
        // 加载角色列表
        async loadRoles() {
            try {
                const response = await fetch('/api/v1/system/roles');
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.roles = result.data.list || [];
                } else {
                    console.warn('加载角色列表失败:', result.message);
                    this.roles = [];
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
                this.roles = [];
            }
        },
        
        // 检查是否有变更
        checkForChanges() {
            if (!this.originalForm || Object.keys(this.originalForm).length === 0) {
                this.hasChanges = false;
                return;
            }
            
            // 比较除密码外的字段
            const currentForm = { ...this.form };
            const originalForm = { ...this.originalForm };
            
            // 如果密码为空，不算作变更
            if (!currentForm.new_password) {
                delete currentForm.new_password;
            }
            delete currentForm.confirm_password;
            delete originalForm.new_password;
            delete originalForm.confirm_password;
            
            this.hasChanges = JSON.stringify(currentForm) !== JSON.stringify(originalForm);
        },
        
        // 检查邮箱是否存在
        async checkEmail() {
            if (!this.form.email) return;
            
            try {
                const response = await fetch(`/api/v1/users/check-email?email=${encodeURIComponent(this.form.email)}&exclude_id=${this.userId}`);
                const result = await response.json();
                
                if (result.code === 200 && result.data && result.data.exists) {
                    this.errors.email = '该邮箱已被其他用户使用';
                } else {
                    this.errors.email = '';
                }
            } catch (error) {
                console.error('检查邮箱失败:', error);
            }
        },
        
        // 切换角色选择
        toggleRole(roleId) {
            const numericRoleId = parseInt(roleId);
            const index = this.form.role_ids.indexOf(numericRoleId);
            
            if (index > -1) {
                // 如果已选中，则移除
                this.form.role_ids.splice(index, 1);
            } else {
                // 如果未选中，则添加
                this.form.role_ids.push(numericRoleId);
            }
            
            // 检查变更
            this.checkForChanges();
        },
        
        // 验证表单
        validateForm() {
            let isValid = true;
            
            // 真实姓名验证
            if (!this.form.real_name.trim()) {
                this.showToast('真实姓名不能为空', 'error');
                isValid = false;
            } else if (this.form.real_name.length > 50) {
                this.showToast('真实姓名不能超过50个字符', 'error');
                isValid = false;
            }
            
            // 密码验证（仅在设置密码时）
            if (this.form.new_password) {
                if (this.form.new_password.length < 6) {
                    this.showToast('密码至少需要6个字符', 'error');
                    isValid = false;
                } else if (this.form.new_password.length > 100) {
                    this.showToast('密码不能超过100个字符', 'error');
                    isValid = false;
                }
            }
            
            // 检查密码确认
            if (this.form.new_password && this.form.new_password !== this.form.confirm_password) {
                this.errors.confirm_password = '两次输入的密码不一致';
                isValid = false;
            } else {
                this.errors.confirm_password = '';
            }
            
            // 邮箱验证
            if (this.form.email && !this.isValidEmail(this.form.email)) {
                this.errors.email = '邮箱格式不正确';
                isValid = false;
            } else {
                this.errors.email = '';
            }
            
            // 手机号验证
            if (this.form.phone && !this.isValidPhone(this.form.phone)) {
                this.showToast('手机号格式不正确', 'error');
                isValid = false;
            }
            
            // 角色验证
            if (!this.form.role_ids || this.form.role_ids.length === 0) {
                this.showToast('请至少选择一个角色', 'error');
                isValid = false;
            }
            
            return isValid;
        },
        
        // 邮箱格式验证
        isValidEmail(email) {
            const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            return emailRegex.test(email);
        },
        
        // 手机号格式验证
        isValidPhone(phone) {
            // 支持中国大陆手机号
            const phoneRegex = /^1[3-9]\d{9}$/;
            return phoneRegex.test(phone);
        },
        
        // 提交表单
        async submitForm() {
            if (!this.validateForm()) return;
            
            this.isSubmitting = true;
            
            try {
                const requestData = {
                    real_name: this.form.real_name,
                    phone: this.form.phone,
                    email: this.form.email,
                    status: this.form.status,
                    role_ids: this.form.role_ids
                };
                
                // 只有在有新密码时才发送密码字段
                if (this.form.new_password) {
                    requestData.password = this.form.new_password;
                }
                
                const response = await fetch(`/api/v1/users/${this.userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('用户信息更新成功', 'success');
                    this.hasChanges = false;
                    // 跳转到用户列表页
                    setTimeout(() => {
                        window.location.href = '/system/users';
                    }, 1500);
                } else {
                    throw new Error(result.message || '更新用户失败');
                }
            } catch (error) {
                console.error('更新用户失败:', error);
                this.showToast('更新用户失败: ' + error.message, 'error');
            } finally {
                this.isSubmitting = false;
            }
        },
        
        // 取消编辑
        cancelEdit() {
            if (this.hasChanges) {
                if (confirm('您有未保存的更改，确定要取消吗？')) {
                    this.hasChanges = false;
                    window.location.href = '/system/users';
                }
            } else {
                window.location.href = '/system/users';
            }
        },
        
        // 重置表单
        resetForm() {
            if (confirm('确定要重置表单吗？这将丢失所有未保存的更改。')) {
                this.form = JSON.parse(JSON.stringify(this.originalForm));
                this.hasChanges = false;
                this.showToast('表单已重置', 'info');
            }
        },
        
        // 显示提示消息
        showToast(message, type = 'info') {
            if (window.showToast) {
                window.showToast(message, type);
            } else {
                // 降级方案
                console.log(`${type}: ${message}`);
                alert(message);
            }
        }
    };
}
</script>
{{end}}